package de.justphil.tcg.tcgserver.rest.db.mapstores.helpers;

import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import de.justphil.tcg.tcgserver.commons.domain.CardInstance;
import de.justphil.tcg.tcgserver.commons.domain.Deck;
import de.justphil.tcg.tcgserver.commons.domain.Game;
import de.justphil.tcg.tcgserver.commons.domain.User;

public class LoadHelper {
	
	public static void loadIncludingDecks(EntityManager em, CardInstance ci) {
		/*
		
		
		Query q = em.createNativeQuery("SELECT deck_id FROM deck_card_instances WHERE card_instance_id = ?", Long.class);
		q.setParameter(1, ci.getId());
		if (q.getResultList() != null && q.getResultList().size() > 0) {
			for ( Long deckId : q.getResultList() ) {
				
			}
		}
		*/
		
		
		
		Set<Long> includingDecks = ci.getDecks();
		
		TypedQuery<Deck> query = em.createQuery("SELECT d FROM Deck d JOIN d.cardInstances ci WHERE ci.id = :ciId", Deck.class);
		
		query.setParameter("ciId", ci.getId());
		
		if (query.getResultList() != null && query.getResultList().size() > 0) {
			for (Deck deck : query.getResultList()) {
				includingDecks.add(deck.getId());
			}
		}
		
		/*
		//Query query = em.createNativeQuery("select D.deck_id AS deck_id from DECKS D, DECK_CARD_INSTANCES CI WHERE D.DECK_ID = CI.DECK_ID AND CI.CARD_INSTANCE_ID = ?", Deck.class);
		Query query = em.createNativeQuery("SELECT decks.id FROM decks", Deck.class);
		//query.setParameter(1, ci.getId());
		
		if (query.getResultList() != null && query.getResultList().size() > 0) {
			List<Deck> decks = castList(Deck.class, query.getResultList());
			
			for (Deck d : decks) {
				includingDecks.add(d.getId());
			}
		}
		*/
		
		
		
		/*
		Set<Long> includingDecks = ci.getDecks();
		
		User user = em.find(User.class, ci.getUserId());
		
		for (Deck deck : user.getDecks()) {
			if (deck.getCardInstances().contains(ci)) {
				includingDecks.add( deck.getId() );
			}
		}
		*/
	}
	
	public static void loadGamePlayers(EntityManager em, Game g) {
		
		Set<Long> gamePlayers = g.getPlayers();
		
		TypedQuery<User> query = em.createQuery("SELECT u FROM User u JOIN u.games g WHERE g.id = :gameId", User.class);
		
		query.setParameter("gameId", g.getId());
		
		if (query.getResultList() != null && query.getResultList().size() > 0) {
			for (User player : query.getResultList()) {
				gamePlayers.add(player.getId());
			}
		}
		
	}
	
	/*
	public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
		List<T> r = new ArrayList<T>(c.size());
		
		for(Object o: c) {
			r.add(clazz.cast(o));
		}
		
	    return r;
	}
	*/


}
